package com.ultrawise.survey.common.utils;

import java.io.*;
import java.util.*;

public class ReadFile {
  private String currentRecord = null;
  private BufferedReader file;
  private String path;
  private StringTokenizer token;
  private boolean isExists;

  /**
   * 创建文件对象
   */
  public ReadFile() {
    file = new BufferedReader(new InputStreamReader(System.in), 1);
  }

  public ReadFile(String filePath) throws FileNotFoundException {
    path = filePath;
    file = new BufferedReader(new FileReader(path));
  }

  /**
   * 设置文件路径
   * @param filePath String
   */
  public void OpenFile(String filePath) {
    path = filePath;
    try {
      isExists = true;
      file = new BufferedReader(new FileReader(path));
    }
    catch (FileNotFoundException e) {
      isExists = false;
      System.out.println("错误：文件没有找到。");
    }
  }

  /**
   * 返回文件是否已经存在
   * @return boolean
   */
  public boolean isExists() {
    return isExists;
  }

  /**
   * 得到文件路径
   * @return String
   */
  public String getPath() {
    return path;
  }

  /**
   * 关闭文件
   * @throws IOException
   */
  public void CloseFile() throws IOException {
    file.close();
  }

  /**
   * 读取下一行记录，若没有则返回-1
   * @return int
   */
  public int nextRecord() {
    int returnInt = -1;
    try {
      currentRecord = file.readLine();
    }
    catch (IOException e) {
      System.out.println("读行错误，结束。");
    }
    if (currentRecord == null) {
      returnInt = -1;
    }
    else {
      token = new StringTokenizer(currentRecord);
      returnInt = token.countTokens();
    }
    return returnInt;
  }

  /**
   * 以字符串的形式返回整行内容
   * @return String
   */
  public String returnRecord() {
    return currentRecord;
  }
}
